package com.sprite.framework.start.container;

import com.sprite.framework.context.ContextEnvironment;
import com.sprite.framework.start.Container;
import com.sprite.framework.start.util.ContainerUtils;
import com.sprite.utils.UtilMisc;

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;

public class MvnContainer implements Container{
	@Override
	public void init(String[] args) {

	}

	@Override
	public void start() {
		try {
			// 更新jar
			downloadJars();

			String script = ContextEnvironment.getProperty("launcher.script");

			if(script.startsWith(File.separator) || script.startsWith("/")) {
				throw new RuntimeException("launcher.script must relative path");
			}
			String[] cmds = {script, getClasspath()};

			System.out.println(UtilMisc.toList(cmds));
			ProcessBuilder builder = new ProcessBuilder(cmds);
			builder.inheritIO();
			builder.start();

			Thread.sleep(2000);

		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("LuancherContainer end!");
	}

	@Override
	public void stop() {
		// TODO Auto-generated method stub

	}

	private String getClasspath() throws Exception {
		String scriptMvn = ContextEnvironment.getProperty("launcher.mvnpath");

		String classpathFile = "cp.temp";
		String[] cmds = {scriptMvn, "dependency:build-classpath", "-Dmdep.outputFile="+classpathFile};

		System.out.println(UtilMisc.toList(cmds));

		Process process = Runtime.getRuntime().exec(cmds);

		log(process);

		String userDir = System.getProperty("user.dir");
		Path cPath = Paths.get(userDir, classpathFile);

		File file = cPath.toFile();
		if(file.exists()) {
			String classpath =  ContainerUtils.readContent(new FileInputStream(file));
			//file.delete();
			return "\""+classpath+"\"";
		}

		return null;
	}

	private void downloadJars() throws IOException {
		String scriptMvn = ContextEnvironment.getProperty("launcher.mvnpath");
		String[] cmds = {scriptMvn, "dependency:go-offline"};
		Process process = Runtime.getRuntime().exec(cmds);

		log(process);
	}

	private void print(InputStream inputStream) throws IOException {
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

		String line = null;
		while((line =bufferedReader.readLine()) != null ) {
			System.out.println(line);
		}
	}


	private void log(Process process) throws IOException {
		{
			System.out.println("output->");
			print(process.getInputStream());

		}


		{
			System.out.println("error->");
			print(process.getErrorStream());
		}
	}


}
